<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="MySQL 索引优化与查询优化, Gtwff">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '');
</script>


    <title>MySQL 索引优化与查询优化 | Gtwff</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Gtwff</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Gtwff</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/kuangty/kuangty" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/kuangty/kuangty" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/14.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">MySQL 索引优化与查询优化</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/MySQL-%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96%E4%B8%8E%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96/">
                                <span class="chip bg-color">MySQL 索引优化与查询优化</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/MySQL/" class="post-category">
                                MySQL
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-10-31
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-03-27
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    31 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="MySQL索引优化与查询优化"><a href="#MySQL索引优化与查询优化" class="headerlink" title="MySQL索引优化与查询优化"></a>MySQL索引优化与查询优化</h1><p>索引我们都经常使用，但是你是否真正的搞懂了索引的正确使用方式呢？今天，我就带你好好看看索引的正确使用姿势以及优化。</p>
<h2 id="1、数据准备"><a href="#1、数据准备" class="headerlink" title="1、数据准备"></a>1、数据准备</h2><p>在正式开始讲解之前，我们先准备一些演示的数据，正所谓磨刀不误砍柴工嘛！</p>
<p>学员表 插 50万 条， 班级表 插 1万 条。</p>
<p><strong>步骤1：建表</strong></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span>class<span class="token punctuation">`</span> <span class="token punctuation">(</span>
    <span class="token punctuation">`</span>id<span class="token punctuation">`</span> <span class="token keyword">INT</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>className<span class="token punctuation">`</span> <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>address<span class="token punctuation">`</span> <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">40</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>monitor<span class="token punctuation">`</span> <span class="token keyword">INT</span> <span class="token boolean">NULL</span> <span class="token punctuation">,</span>
    <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>id<span class="token punctuation">`</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span> <span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">INNODB</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token operator">=</span><span class="token number">1</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8<span class="token punctuation">;</span>

<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span>student<span class="token punctuation">`</span> <span class="token punctuation">(</span>
    <span class="token punctuation">`</span>id<span class="token punctuation">`</span> <span class="token keyword">INT</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>stuno<span class="token punctuation">`</span> <span class="token keyword">INT</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token punctuation">,</span>
    <span class="token punctuation">`</span>name<span class="token punctuation">`</span> <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>age<span class="token punctuation">`</span> <span class="token keyword">INT</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>classId<span class="token punctuation">`</span> <span class="token keyword">INT</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
    <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>id<span class="token punctuation">`</span><span class="token punctuation">)</span>
    <span class="token comment">#CONSTRAINT `fk_class_id` FOREIGN KEY (`classId`) REFERENCES `t_class` (`id`)</span>
<span class="token punctuation">)</span> <span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">INNODB</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token operator">=</span><span class="token number">1</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>步骤2：设置参数</strong><br>命令开启：允许创建函数设置：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">set</span> <span class="token keyword">global</span> log_bin_trust_function_creators<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span> <span class="token comment"># 不加global只是当前窗口有效。</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><strong>步骤3：创建函数</strong><br>保证每条数据都不同。  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#随机产生字符串</span>
<span class="token keyword">DELIMITER</span> <span class="token comment">//</span>
<span class="token keyword">CREATE</span> <span class="token keyword">FUNCTION</span> rand_string<span class="token punctuation">(</span>n <span class="token keyword">INT</span><span class="token punctuation">)</span> <span class="token keyword">RETURNS</span> <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span>
<span class="token keyword">BEGIN</span>
<span class="token keyword">DECLARE</span> chars_str <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token string">'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ'</span><span class="token punctuation">;</span>
<span class="token keyword">DECLARE</span> return_str <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token string">''</span><span class="token punctuation">;</span>
<span class="token keyword">DECLARE</span> i <span class="token keyword">INT</span> <span class="token keyword">DEFAULT</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">WHILE</span> i <span class="token operator">&lt;</span> n <span class="token keyword">DO</span>
<span class="token keyword">SET</span> return_str <span class="token operator">=</span>CONCAT<span class="token punctuation">(</span>return_str<span class="token punctuation">,</span>SUBSTRING<span class="token punctuation">(</span>chars_str<span class="token punctuation">,</span>FLOOR<span class="token punctuation">(</span><span class="token number">1</span><span class="token operator">+</span>RAND<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">*</span><span class="token number">52</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">SET</span> i <span class="token operator">=</span> i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
<span class="token keyword">END</span> <span class="token keyword">WHILE</span><span class="token punctuation">;</span>
<span class="token keyword">RETURN</span> return_str<span class="token punctuation">;</span>
<span class="token keyword">END</span> <span class="token comment">//</span>
<span class="token keyword">DELIMITER</span><span class="token punctuation">;</span>

<span class="token comment">#假如要删除</span>
<span class="token comment">#drop function rand_string;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>步骤4：创建存储过程</strong>  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#创建往stu表中插入数据的存储过程</span>
<span class="token keyword">DELIMITER</span> <span class="token comment">//</span>
<span class="token keyword">CREATE</span> <span class="token keyword">PROCEDURE</span> insert_stu<span class="token punctuation">(</span> <span class="token keyword">START</span> <span class="token keyword">INT</span> <span class="token punctuation">,</span> max_num <span class="token keyword">INT</span> <span class="token punctuation">)</span>
<span class="token keyword">BEGIN</span>
<span class="token keyword">DECLARE</span> i <span class="token keyword">INT</span> <span class="token keyword">DEFAULT</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">SET</span> autocommit <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> <span class="token comment">#设置手动提交事务</span>
<span class="token keyword">REPEAT</span> <span class="token comment">#循环</span>
<span class="token keyword">SET</span> i <span class="token operator">=</span> i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span> <span class="token comment">#赋值</span>
<span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> student <span class="token punctuation">(</span>stuno<span class="token punctuation">,</span> name <span class="token punctuation">,</span>age <span class="token punctuation">,</span>classId <span class="token punctuation">)</span> <span class="token keyword">VALUES</span>
<span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">START</span><span class="token operator">+</span>i<span class="token punctuation">)</span><span class="token punctuation">,</span>rand_string<span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">,</span>rand_num<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">50</span><span class="token punctuation">)</span><span class="token punctuation">,</span>rand_num<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
UNTIL i <span class="token operator">=</span> max_num
<span class="token keyword">END</span> <span class="token keyword">REPEAT</span><span class="token punctuation">;</span>
<span class="token keyword">COMMIT</span><span class="token punctuation">;</span> <span class="token comment">#提交事务</span>
<span class="token keyword">END</span> <span class="token comment">//</span>
<span class="token keyword">DELIMITER</span><span class="token punctuation">;</span>

<span class="token comment">#假如要删除</span>
<span class="token comment">#drop PROCEDURE insert_stu;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>创建往class表中插入数据的存储过程  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#执行存储过程，往class表添加随机数据</span>
<span class="token keyword">DELIMITER</span> <span class="token comment">//</span>
<span class="token keyword">CREATE</span> <span class="token keyword">PROCEDURE</span> <span class="token punctuation">`</span>insert_class<span class="token punctuation">`</span><span class="token punctuation">(</span> max_num <span class="token keyword">INT</span> <span class="token punctuation">)</span>
<span class="token keyword">BEGIN</span>
<span class="token keyword">DECLARE</span> i <span class="token keyword">INT</span> <span class="token keyword">DEFAULT</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">SET</span> autocommit <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">REPEAT</span>
<span class="token keyword">SET</span> i <span class="token operator">=</span> i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
<span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> class <span class="token punctuation">(</span> classname<span class="token punctuation">,</span>address<span class="token punctuation">,</span>monitor <span class="token punctuation">)</span> <span class="token keyword">VALUES</span>
<span class="token punctuation">(</span>rand_string<span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">,</span>rand_string<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">,</span>rand_num<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">100000</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
UNTIL i <span class="token operator">=</span> max_num
<span class="token keyword">END</span> <span class="token keyword">REPEAT</span><span class="token punctuation">;</span>
<span class="token keyword">COMMIT</span><span class="token punctuation">;</span>
<span class="token keyword">END</span> <span class="token comment">//</span>
<span class="token keyword">DELIMITER</span> <span class="token punctuation">;</span>
<span class="token comment">#假如要删除</span>
<span class="token comment">#drop PROCEDURE insert_class;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>步骤5：调用存储过程</strong><br>class 表：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#执行存储过程，往class表添加1万条数据</span>
<span class="token keyword">CALL</span> insert_class<span class="token punctuation">(</span><span class="token number">10000</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>student 表：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#执行存储过程，往stu表添加50万条数据</span>
<span class="token keyword">CALL</span> insert_stu<span class="token punctuation">(</span><span class="token number">100000</span><span class="token punctuation">,</span><span class="token number">500000</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><strong>步骤6：删除某表上的索引</strong><br>创建存储过程</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">DELIMITER</span> <span class="token comment">//</span>
<span class="token keyword">CREATE</span> <span class="token keyword">PROCEDURE</span> <span class="token punctuation">`</span>proc_drop_index<span class="token punctuation">`</span><span class="token punctuation">(</span>dbname <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">)</span><span class="token punctuation">,</span>tablename <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">BEGIN</span>
    <span class="token keyword">DECLARE</span> done <span class="token keyword">INT</span> <span class="token keyword">DEFAULT</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">DECLARE</span> ct <span class="token keyword">INT</span> <span class="token keyword">DEFAULT</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">DECLARE</span> _index <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token string">''</span><span class="token punctuation">;</span>
    <span class="token keyword">DECLARE</span> _cur <span class="token keyword">CURSOR</span> <span class="token keyword">FOR</span> <span class="token keyword">SELECT</span> index_name <span class="token keyword">FROM</span>
information_schema<span class="token punctuation">.</span><span class="token keyword">STATISTICS</span> <span class="token keyword">WHERE</span> table_schema<span class="token operator">=</span>dbname <span class="token operator">AND</span> table_name<span class="token operator">=</span>tablename <span class="token operator">AND</span>
seq_in_index<span class="token operator">=</span><span class="token number">1</span> <span class="token operator">AND</span> index_name <span class="token operator">&lt;></span><span class="token string">'PRIMARY'</span> <span class="token punctuation">;</span>
<span class="token comment">#每个游标必须使用不同的declare continue handler for not found set done=1来控制游标的结束</span>
	<span class="token keyword">DECLARE</span> <span class="token keyword">CONTINUE</span> <span class="token keyword">HANDLER</span> <span class="token keyword">FOR</span> <span class="token operator">NOT</span> FOUND <span class="token keyword">set</span> done<span class="token operator">=</span><span class="token number">2</span> <span class="token punctuation">;</span>
<span class="token comment">#若没有数据返回,程序继续,并将变量done设为2</span>
	<span class="token keyword">OPEN</span> _cur<span class="token punctuation">;</span>
	<span class="token keyword">FETCH</span> _cur <span class="token keyword">INTO</span> _index<span class="token punctuation">;</span>
	<span class="token keyword">WHILE</span> _index<span class="token operator">&lt;></span><span class="token string">''</span> <span class="token keyword">DO</span>
        <span class="token keyword">SET</span> <span class="token variable">@str</span> <span class="token operator">=</span> CONCAT<span class="token punctuation">(</span><span class="token string">"drop index "</span> <span class="token punctuation">,</span> _index <span class="token punctuation">,</span> <span class="token string">" on "</span> <span class="token punctuation">,</span> tablename <span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">PREPARE</span> sql_str <span class="token keyword">FROM</span> <span class="token variable">@str</span> <span class="token punctuation">;</span>
        <span class="token keyword">EXECUTE</span> sql_str<span class="token punctuation">;</span>
        <span class="token keyword">DEALLOCATE</span> <span class="token keyword">PREPARE</span> sql_str<span class="token punctuation">;</span>
        <span class="token keyword">SET</span> _index<span class="token operator">=</span><span class="token string">''</span><span class="token punctuation">;</span>
        <span class="token keyword">FETCH</span> _cur <span class="token keyword">INTO</span> _index<span class="token punctuation">;</span>
	<span class="token keyword">END</span> <span class="token keyword">WHILE</span><span class="token punctuation">;</span>
  <span class="token keyword">CLOSE</span> _cur<span class="token punctuation">;</span>
<span class="token keyword">END</span> <span class="token comment">//</span>
<span class="token keyword">DELIMITER</span> <span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>执行存储过程</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CALL</span> proc_drop_index<span class="token punctuation">(</span><span class="token string">"dbname"</span><span class="token punctuation">,</span><span class="token string">"tablename"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="2、索引失效案例"><a href="#2、索引失效案例" class="headerlink" title="2、索引失效案例"></a>2、索引失效案例</h2><h4 id="1、全值匹配我最爱"><a href="#1、全值匹配我最爱" class="headerlink" title="1、全值匹配我最爱"></a>1、全值匹配我最爱</h4><p>全值匹配会使用到索引，而且对于联合索引来说，就算顺序不对也会使用索引，优化器会优化。</p>
<h4 id="2、最佳左前缀法则"><a href="#2、最佳左前缀法则" class="headerlink" title="2、最佳左前缀法则"></a>2、最佳左前缀法则</h4><p>索引文件具有 B-Tree 的最左前缀匹配特性，如果左边的值未确定，那么无法使用此索引。  </p>
<h4 id="3、主键插入顺序"><a href="#3、主键插入顺序" class="headerlink" title="3、主键插入顺序"></a>3、主键插入顺序</h4><p>初始数据：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112421232.png" alt="image-20220327112421232" style="zoom:80%;" />

<p>如果此时再插入一条主键值为 9 的记录，那它插入的位置就如下图  </p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112415603.png" alt="image-20220327112415603" style="zoom:80%;" />

<p>可这个数据页已经满了，再插进来咋办呢？我们需要把当前 页面分裂 成两个页面，把本页中的一些记录移动到新创建的这个页中。页面分裂和记录移位意味着什么？意味着： 性能损耗 ！所以如果我们想尽量避免这样无谓的性能损耗，最好让插入的记录的 主键值依次递增 ，这样就不会发生这样的性能损耗了。所以我们建议：让主键具有 AUTO_INCREMENT ，让存储引擎自己为表生成主键，而不是我们手动插入 ，比如： person_info 表  </p>
<pre class="line-numbers language-SQL" data-language="SQL"><code class="language-SQL">CREATE TABLE person_info(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    birthday DATE NOT NULL,
    phone_number CHAR(11) NOT NULL,
    country varchar(100) NOT NULL,
    PRIMARY KEY (id),
    KEY idx_name_birthday_phone_number (name(10), birthday, phone_number)
);<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>我们自定义的主键列 id 拥有 AUTO_INCREMENT 属性，在插入记录时存储引擎会自动为我们填入自增的主键值。这样的主键占用空间小，顺序写入，减少页分裂。  </p>
<h4 id="4、计算、函数、类型转换-自动或手动-导致索引失效"><a href="#4、计算、函数、类型转换-自动或手动-导致索引失效" class="headerlink" title="4、计算、函数、类型转换(自动或手动)导致索引失效"></a>4、计算、函数、类型转换(自动或手动)导致索引失效</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> student<span class="token punctuation">.</span>name <span class="token operator">LIKE</span> <span class="token string">'abc%'</span><span class="token punctuation">;</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> <span class="token keyword">LEFT</span><span class="token punctuation">(</span>student<span class="token punctuation">.</span>name<span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token string">'abc'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>创建索引</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">INDEX</span> idx_name <span class="token keyword">ON</span> student<span class="token punctuation">(</span>NAME<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>第一种：索引优化生效  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> student<span class="token punctuation">.</span>name <span class="token operator">LIKE</span> <span class="token string">'abc%'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> student<span class="token punctuation">.</span>name <span class="token operator">LIKE</span> <span class="token string">'abc%'</span><span class="token punctuation">;</span>
<span class="token operator">+</span><span class="token comment">---------+---------+--------+------+---------+</span>
<span class="token operator">|</span> id      <span class="token operator">|</span> stuno   <span class="token operator">|</span> name   <span class="token operator">|</span> age  <span class="token operator">|</span> classId <span class="token operator">|</span>
<span class="token operator">+</span><span class="token comment">---------+---------+--------+------+---------+</span>
<span class="token operator">|</span> <span class="token number">5301379</span> <span class="token operator">|</span> <span class="token number">1233401</span> <span class="token operator">|</span> AbCHEa <span class="token operator">|</span> <span class="token number">164</span> <span class="token operator">|</span> <span class="token number">259</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">7170042</span> <span class="token operator">|</span> <span class="token number">3102064</span> <span class="token operator">|</span> ABcHeB <span class="token operator">|</span> <span class="token number">199</span> <span class="token operator">|</span> <span class="token number">161</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1901614</span> <span class="token operator">|</span> <span class="token number">1833636</span> <span class="token operator">|</span> ABcHeC <span class="token operator">|</span> <span class="token number">226</span> <span class="token operator">|</span> <span class="token number">275</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">5195021</span> <span class="token operator">|</span> <span class="token number">1127043</span> <span class="token operator">|</span> abchEC <span class="token operator">|</span> <span class="token number">486</span> <span class="token operator">|</span> <span class="token number">72</span>  <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4047089</span> <span class="token operator">|</span> <span class="token number">3810031</span> <span class="token operator">|</span> AbCHFd <span class="token operator">|</span> <span class="token number">268</span> <span class="token operator">|</span> <span class="token number">210</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4917074</span> <span class="token operator">|</span> <span class="token number">849096</span>  <span class="token operator">|</span> ABcHfD <span class="token operator">|</span> <span class="token number">264</span> <span class="token operator">|</span> <span class="token number">442</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1540859</span> <span class="token operator">|</span> <span class="token number">141979</span>  <span class="token operator">|</span> abchFF <span class="token operator">|</span> <span class="token number">119</span> <span class="token operator">|</span> <span class="token number">140</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">5121801</span> <span class="token operator">|</span> <span class="token number">1053823</span> <span class="token operator">|</span> AbCHFg <span class="token operator">|</span> <span class="token number">412</span> <span class="token operator">|</span> <span class="token number">327</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">2441254</span> <span class="token operator">|</span> <span class="token number">2373276</span> <span class="token operator">|</span> abchFJ <span class="token operator">|</span> <span class="token number">170</span> <span class="token operator">|</span> <span class="token number">362</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">7039146</span> <span class="token operator">|</span> <span class="token number">2971168</span> <span class="token operator">|</span> ABcHgI <span class="token operator">|</span> <span class="token number">502</span> <span class="token operator">|</span> <span class="token number">465</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1636826</span> <span class="token operator">|</span> <span class="token number">1580286</span> <span class="token operator">|</span> ABcHgK <span class="token operator">|</span> <span class="token number">71</span>  <span class="token operator">|</span> <span class="token number">262</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">374344</span>  <span class="token operator">|</span> <span class="token number">474345</span> <span class="token operator">|</span> abchHL  <span class="token operator">|</span> <span class="token number">367</span> <span class="token operator">|</span> <span class="token number">212</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1596534</span> <span class="token operator">|</span> <span class="token number">169191</span> <span class="token operator">|</span> AbCHHl  <span class="token operator">|</span> <span class="token number">102</span> <span class="token operator">|</span> <span class="token number">146</span> <span class="token operator">|</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token operator">|</span> <span class="token number">5266837</span> <span class="token operator">|</span> <span class="token number">1198859</span> <span class="token operator">|</span> abclXe <span class="token operator">|</span> <span class="token number">292</span> <span class="token operator">|</span> <span class="token number">298</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">8126968</span> <span class="token operator">|</span> <span class="token number">4058990</span> <span class="token operator">|</span> aBClxE <span class="token operator">|</span> <span class="token number">316</span> <span class="token operator">|</span> <span class="token number">150</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4298305</span> <span class="token operator">|</span> <span class="token number">399962</span>  <span class="token operator">|</span> AbCLXF <span class="token operator">|</span> <span class="token number">72</span>  <span class="token operator">|</span> <span class="token number">423</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">5813628</span> <span class="token operator">|</span> <span class="token number">1745650</span> <span class="token operator">|</span> aBClxF <span class="token operator">|</span> <span class="token number">356</span> <span class="token operator">|</span> <span class="token number">323</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">6980448</span> <span class="token operator">|</span> <span class="token number">2912470</span> <span class="token operator">|</span> AbCLXF <span class="token operator">|</span> <span class="token number">107</span> <span class="token operator">|</span> <span class="token number">78</span>  <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">7881979</span> <span class="token operator">|</span> <span class="token number">3814001</span> <span class="token operator">|</span> AbCLXF <span class="token operator">|</span> <span class="token number">89</span>  <span class="token operator">|</span> <span class="token number">497</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4955576</span> <span class="token operator">|</span> <span class="token number">887598</span>  <span class="token operator">|</span> ABcLxg <span class="token operator">|</span> <span class="token number">121</span> <span class="token operator">|</span> <span class="token number">385</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">3653460</span> <span class="token operator">|</span> <span class="token number">3585482</span> <span class="token operator">|</span> AbCLXJ <span class="token operator">|</span> <span class="token number">130</span> <span class="token operator">|</span> <span class="token number">174</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1231990</span> <span class="token operator">|</span> <span class="token number">1283439</span> <span class="token operator">|</span> AbCLYH <span class="token operator">|</span> <span class="token number">189</span> <span class="token operator">|</span> <span class="token number">429</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">6110615</span> <span class="token operator">|</span> <span class="token number">2042637</span> <span class="token operator">|</span> ABcLyh <span class="token operator">|</span> <span class="token number">157</span> <span class="token operator">|</span> <span class="token number">40</span>  <span class="token operator">|</span>
<span class="token operator">+</span><span class="token comment">---------+---------+--------+------+---------+</span>
<span class="token number">401</span> <span class="token keyword">rows</span> <span class="token operator">in</span> <span class="token keyword">set</span><span class="token punctuation">,</span> <span class="token number">1</span> warning <span class="token punctuation">(</span><span class="token number">0.01</span> sec<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>第二种：索引优化失效  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> <span class="token keyword">LEFT</span><span class="token punctuation">(</span>student<span class="token punctuation">.</span>name<span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token string">'abc'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112430212.png" alt="image-20220327112430212" style="zoom:80%;" />

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> <span class="token keyword">LEFT</span><span class="token punctuation">(</span>student<span class="token punctuation">.</span>name<span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token string">'abc'</span><span class="token punctuation">;</span>
<span class="token operator">+</span><span class="token comment">---------+---------+--------+------+---------+</span>
<span class="token operator">|</span> id      <span class="token operator">|</span> stuno   <span class="token operator">|</span> name   <span class="token operator">|</span> age  <span class="token operator">|</span> classId <span class="token operator">|</span>
<span class="token operator">+</span><span class="token comment">---------+---------+--------+------+---------+</span>
<span class="token operator">|</span> <span class="token number">5301379</span> <span class="token operator">|</span> <span class="token number">1233401</span> <span class="token operator">|</span> AbCHEa <span class="token operator">|</span> <span class="token number">164</span> <span class="token operator">|</span> <span class="token number">259</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">7170042</span> <span class="token operator">|</span> <span class="token number">3102064</span> <span class="token operator">|</span> ABcHeB <span class="token operator">|</span> <span class="token number">199</span> <span class="token operator">|</span> <span class="token number">161</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1901614</span> <span class="token operator">|</span> <span class="token number">1833636</span> <span class="token operator">|</span> ABcHeC <span class="token operator">|</span> <span class="token number">226</span> <span class="token operator">|</span> <span class="token number">275</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">5195021</span> <span class="token operator">|</span> <span class="token number">1127043</span> <span class="token operator">|</span> abchEC <span class="token operator">|</span> <span class="token number">486</span> <span class="token operator">|</span> <span class="token number">72</span>  <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4047089</span> <span class="token operator">|</span> <span class="token number">3810031</span> <span class="token operator">|</span> AbCHFd <span class="token operator">|</span> <span class="token number">268</span> <span class="token operator">|</span> <span class="token number">210</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4917074</span> <span class="token operator">|</span> <span class="token number">849096</span>  <span class="token operator">|</span> ABcHfD <span class="token operator">|</span> <span class="token number">264</span> <span class="token operator">|</span> <span class="token number">442</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1540859</span> <span class="token operator">|</span> <span class="token number">141979</span>  <span class="token operator">|</span> abchFF <span class="token operator">|</span> <span class="token number">119</span> <span class="token operator">|</span> <span class="token number">140</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">5121801</span> <span class="token operator">|</span> <span class="token number">1053823</span> <span class="token operator">|</span> AbCHFg <span class="token operator">|</span> <span class="token number">412</span> <span class="token operator">|</span> <span class="token number">327</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">2441254</span> <span class="token operator">|</span> <span class="token number">2373276</span> <span class="token operator">|</span> abchFJ <span class="token operator">|</span> <span class="token number">170</span> <span class="token operator">|</span> <span class="token number">362</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">7039146</span> <span class="token operator">|</span> <span class="token number">2971168</span> <span class="token operator">|</span> ABcHgI <span class="token operator">|</span> <span class="token number">502</span> <span class="token operator">|</span> <span class="token number">465</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1636826</span> <span class="token operator">|</span> <span class="token number">1580286</span> <span class="token operator">|</span> ABcHgK <span class="token operator">|</span> <span class="token number">71</span>  <span class="token operator">|</span> <span class="token number">262</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">374344</span>  <span class="token operator">|</span> <span class="token number">474345</span>  <span class="token operator">|</span> abchHL <span class="token operator">|</span> <span class="token number">367</span> <span class="token operator">|</span> <span class="token number">212</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1596534</span> <span class="token operator">|</span> <span class="token number">169191</span>  <span class="token operator">|</span> AbCHHl <span class="token operator">|</span> <span class="token number">102</span> <span class="token operator">|</span> <span class="token number">146</span> <span class="token operator">|</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token operator">|</span> <span class="token number">5266837</span> <span class="token operator">|</span> <span class="token number">1198859</span> <span class="token operator">|</span> abclXe <span class="token operator">|</span> <span class="token number">292</span> <span class="token operator">|</span> <span class="token number">298</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">8126968</span> <span class="token operator">|</span> <span class="token number">4058990</span> <span class="token operator">|</span> aBClxE <span class="token operator">|</span> <span class="token number">316</span> <span class="token operator">|</span> <span class="token number">150</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4298305</span> <span class="token operator">|</span> <span class="token number">399962</span>  <span class="token operator">|</span> AbCLXF <span class="token operator">|</span> <span class="token number">72</span>  <span class="token operator">|</span> <span class="token number">423</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">5813628</span> <span class="token operator">|</span> <span class="token number">1745650</span> <span class="token operator">|</span> aBClxF <span class="token operator">|</span> <span class="token number">356</span> <span class="token operator">|</span> <span class="token number">323</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">6980448</span> <span class="token operator">|</span> <span class="token number">2912470</span> <span class="token operator">|</span> AbCLXF <span class="token operator">|</span> <span class="token number">107</span> <span class="token operator">|</span> <span class="token number">78</span>  <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">7881979</span> <span class="token operator">|</span> <span class="token number">3814001</span> <span class="token operator">|</span> AbCLXF <span class="token operator">|</span> <span class="token number">89</span>  <span class="token operator">|</span> <span class="token number">497</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">4955576</span> <span class="token operator">|</span> <span class="token number">887598</span>  <span class="token operator">|</span> ABcLxg <span class="token operator">|</span> <span class="token number">121</span> <span class="token operator">|</span> <span class="token number">385</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">3653460</span> <span class="token operator">|</span> <span class="token number">3585482</span> <span class="token operator">|</span> AbCLXJ <span class="token operator">|</span> <span class="token number">130</span> <span class="token operator">|</span> <span class="token number">174</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">1231990</span> <span class="token operator">|</span> <span class="token number">1283439</span> <span class="token operator">|</span> AbCLYH <span class="token operator">|</span> <span class="token number">189</span> <span class="token operator">|</span> <span class="token number">429</span> <span class="token operator">|</span>
<span class="token operator">|</span> <span class="token number">6110615</span> <span class="token operator">|</span> <span class="token number">2042637</span> <span class="token operator">|</span> ABcLyh <span class="token operator">|</span> <span class="token number">157</span> <span class="token operator">|</span> <span class="token number">40</span>  <span class="token operator">|</span>
<span class="token operator">+</span><span class="token comment">---------+---------+--------+------+---------+</span>
<span class="token number">401</span> <span class="token keyword">rows</span> <span class="token operator">in</span> <span class="token keyword">set</span><span class="token punctuation">,</span> <span class="token number">1</span> warning <span class="token punctuation">(</span><span class="token number">3.62</span> sec<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<blockquote>
<p>type为“ALL”，表示没有使用到索引，查询时间为 3.62 秒，查询效率较之前低很多。  </p>
</blockquote>
<h4 id="5、类型转换导致索引失效"><a href="#5、类型转换导致索引失效" class="headerlink" title="5、类型转换导致索引失效"></a>5、类型转换导致索引失效</h4><p>下列哪个sql语句可以用到索引。（假设name字段上设置有索引）  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment"># 未使用到索引</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> name<span class="token operator">=</span><span class="token number">123</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112437064.png" alt="image-20220327112437064" style="zoom:80%;" />

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment"># 使用到索引</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> name<span class="token operator">=</span><span class="token string">'123'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112441899.png" alt="image-20220327112441899" style="zoom:80%;" />

<blockquote>
<p>name=123发生类型转换，索引失效。</p>
</blockquote>
<h4 id="6、范围条件右边的列索引失效"><a href="#6、范围条件右边的列索引失效" class="headerlink" title="6、范围条件右边的列索引失效"></a>6、范围条件右边的列索引失效</h4><pre class="line-numbers language-SQL" data-language="SQL"><code class="language-SQL">ALTER TABLE student DROP INDEX idx_name;
ALTER TABLE student DROP INDEX idx_age;
ALTER TABLE student DROP INDEX idx_age_classid;
EXPLAIN SELECT SQL_NO_CACHE * FROM student
WHERE student.age&#x3D;30 AND student.classId&gt;20 AND student.name &#x3D; &#39;abc&#39; ;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112447607.png" alt="image-20220327112447607" style="zoom:80%;" />

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token keyword">index</span> idx_age_name_classid <span class="token keyword">on</span> student<span class="token punctuation">(</span>age<span class="token punctuation">,</span>name<span class="token punctuation">,</span>classid<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>将范围查询条件放置语句最后：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> student<span class="token punctuation">.</span>age<span class="token operator">=</span><span class="token number">30</span> <span class="token operator">AND</span> student<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">'abc'</span> <span class="token operator">AND</span> student<span class="token punctuation">.</span>classId<span class="token operator">></span><span class="token number">20</span> <span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112453654.png" alt="image-20220327112453654" style="zoom:80%;" />

<h4 id="7、不等于-或者-lt-gt-索引失效"><a href="#7、不等于-或者-lt-gt-索引失效" class="headerlink" title="7、不等于(!= 或者&lt;&gt;)索引失效"></a>7、不等于(!= 或者&lt;&gt;)索引失效</h4><h4 id="8、is-null可以使用索引，is-not-null无法使用索引"><a href="#8、is-null可以使用索引，is-not-null无法使用索引" class="headerlink" title="8、is null可以使用索引，is not null无法使用索引"></a>8、is null可以使用索引，is not null无法使用索引</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> age <span class="token operator">IS</span> <span class="token boolean">NULL</span><span class="token punctuation">;</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> age <span class="token operator">IS</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h4 id="9、like以通配符-开头索引失效"><a href="#9、like以通配符-开头索引失效" class="headerlink" title="9、like以通配符%开头索引失效"></a>9、like以通配符%开头索引失效</h4><p>页面搜索严禁左模糊或者全模糊，如果需要请走搜索引擎来解决。</p>
<h4 id="10、OR-前后存在非索引的列，索引失效"><a href="#10、OR-前后存在非索引的列，索引失效" class="headerlink" title="10、OR 前后存在非索引的列，索引失效"></a>10、OR 前后存在非索引的列，索引失效</h4><pre class="line-numbers language-SQL" data-language="SQL"><code class="language-SQL"># 未使用到索引
EXPLAIN SELECT SQL_NO_CACHE * FROM student WHERE age &#x3D; 10 OR classid &#x3D; 100;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112459144.png" alt="image-20220327112459144" style="zoom:80%;" />

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#使用到索引</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> age <span class="token operator">=</span> <span class="token number">10</span> <span class="token operator">OR</span> name <span class="token operator">=</span> <span class="token string">'Abel'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112504375.png" alt="image-20220327112504375" style="zoom:80%;" />

<h4 id="11、数据库和表的字符集统一使用utf8mb4"><a href="#11、数据库和表的字符集统一使用utf8mb4" class="headerlink" title="11、数据库和表的字符集统一使用utf8mb4"></a>11、数据库和表的字符集统一使用utf8mb4</h4><p>统一使用utf8mb4( 5.5.3版本以上支持)兼容性更好，统一字符集可以避免由于字符集转换产生的乱码。不同的 字符集 进行比较前需要进行 转换 会造成索引失效。  </p>
<h2 id="3、关联查询优化"><a href="#3、关联查询优化" class="headerlink" title="3、关联查询优化"></a>3、关联查询优化</h2><h4 id="1、采用左外连接"><a href="#1、采用左外连接" class="headerlink" title="1、采用左外连接"></a>1、采用左外连接</h4><p>下面开始 EXPLAIN 分析  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token keyword">type</span> <span class="token keyword">LEFT</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card <span class="token operator">=</span> book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112510957.png" alt="image-20220327112510957" style="zoom:80%;" />

<p>结论：type 有All，即没有使用索引。<br>添加索引优化  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">ALTER</span> <span class="token keyword">TABLE</span> book <span class="token keyword">ADD</span> <span class="token keyword">INDEX</span> Y <span class="token punctuation">(</span> card<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">#【被驱动表】，可以避免全表扫描</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token keyword">type</span> <span class="token keyword">LEFT</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card <span class="token operator">=</span> book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112516914.png" alt="image-20220327112516914" style="zoom:80%;" />

<p>可以看到第二行的 type 变为了 ref，rows 也变成了优化比较明显。这是由左连接特性决定的。LEFT JOIN 条件用于确定如何从右表搜索行，左边一定都有，所以 右边是我们的关键点,一定需要建立索引。</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">ALTER</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span><span class="token keyword">type</span><span class="token punctuation">`</span> <span class="token keyword">ADD</span> <span class="token keyword">INDEX</span> X <span class="token punctuation">(</span>card<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">#【驱动表】，无法避免全表扫描</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token punctuation">`</span><span class="token keyword">type</span><span class="token punctuation">`</span> <span class="token keyword">LEFT</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card <span class="token operator">=</span> book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112522660.png" alt="image-20220327112522660" style="zoom:80%;" />

<p>接着：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">DROP</span> <span class="token keyword">INDEX</span> Y <span class="token keyword">ON</span> book<span class="token punctuation">;</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token punctuation">`</span><span class="token keyword">type</span><span class="token punctuation">`</span> <span class="token keyword">LEFT</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card <span class="token operator">=</span> book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112529218.png" alt="image-20220327112529218" style="zoom:80%;" />

<h4 id="2、采用内连接"><a href="#2、采用内连接" class="headerlink" title="2、采用内连接"></a>2、采用内连接</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">drop</span> <span class="token keyword">index</span> X <span class="token keyword">on</span> <span class="token keyword">type</span><span class="token punctuation">;</span>
<span class="token keyword">drop</span> <span class="token keyword">index</span> Y <span class="token keyword">on</span> book<span class="token punctuation">;</span>（如果已经删除了可以不用再执行该操作）<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>换成 inner join（MySQL自动选择驱动表）  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token keyword">type</span> <span class="token keyword">INNER</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card<span class="token operator">=</span>book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112535107.png" alt="image-20220327112535107" style="zoom:80%;" />

<p>添加索引优化</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">ALTER</span> <span class="token keyword">TABLE</span> book <span class="token keyword">ADD</span> <span class="token keyword">INDEX</span> Y <span class="token punctuation">(</span> card<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token keyword">type</span> <span class="token keyword">INNER</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card<span class="token operator">=</span>book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112540839.png" alt="image-20220327112540839" style="zoom:80%;" />

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">ALTER</span> <span class="token keyword">TABLE</span> <span class="token keyword">type</span> <span class="token keyword">ADD</span> <span class="token keyword">INDEX</span> X <span class="token punctuation">(</span>card<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token keyword">type</span> <span class="token keyword">INNER</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card<span class="token operator">=</span>book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112548553.png" alt="image-20220327112548553" style="zoom:80%;" />

<p>接着：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">DROP</span> <span class="token keyword">INDEX</span> X <span class="token keyword">ON</span> <span class="token punctuation">`</span><span class="token keyword">type</span><span class="token punctuation">`</span><span class="token punctuation">;</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token keyword">TYPE</span> <span class="token keyword">INNER</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card<span class="token operator">=</span>book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112554028.png" alt="image-20220327112554028" style="zoom:80%;" />

<p>接着：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">ALTER</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span><span class="token keyword">type</span><span class="token punctuation">`</span> <span class="token keyword">ADD</span> <span class="token keyword">INDEX</span> X <span class="token punctuation">(</span>card<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> SQL_NO_CACHE <span class="token operator">*</span> <span class="token keyword">FROM</span> <span class="token punctuation">`</span><span class="token keyword">type</span><span class="token punctuation">`</span> <span class="token keyword">INNER</span> <span class="token keyword">JOIN</span> book <span class="token keyword">ON</span> <span class="token keyword">type</span><span class="token punctuation">.</span>card<span class="token operator">=</span>book<span class="token punctuation">.</span>card<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112559385.png" alt="image-20220327112559385" style="zoom:80%;" />

<h4 id="3、join语句原理"><a href="#3、join语句原理" class="headerlink" title="3、join语句原理"></a>3、join语句原理</h4><p>我们来看一下这个语句：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> <span class="token operator">*</span> <span class="token keyword">FROM</span> t1 STRAIGHT_JOIN t2 <span class="token keyword">ON</span> <span class="token punctuation">(</span>t1<span class="token punctuation">.</span>a<span class="token operator">=</span>t2<span class="token punctuation">.</span>a<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>如果直接使用join语句，MySQL优化器可能会选择表t1或t2作为驱动表，这样会影响我们分析SQL语句的执行过程。所以，为了便于分析执行过程中的性能问题，我改用 straight_join 让MySQL使用固定的连接方式执行查询，这样优化器只会按照我们指定的方式去join。在这个语句里，t1 是驱动表，t2是被驱动表。  </p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112604933.png" alt="image-20220327112604933" style="zoom:80%;" />

<p>可以看到，在这条语句里，被驱动表t2的字段a上有索引，join过程用上了这个索引，因此这个语句的执<br>行流程是这样的：</p>
<ol>
<li>从表t1中读入一行数据 R；</li>
<li>从数据行R中，取出a字段到表t2里去查找；</li>
<li>取出表t2中满足条件的行，跟R组成一行，作为结果集的一部分；</li>
<li>重复执行步骤1到3，直到表t1的末尾循环结束。</li>
</ol>
<p>这个过程是先遍历表t1，然后根据从表t1中取出的每行数据中的a值，去表t2中查找满足条件的记录。在形式上，这个过程就跟我们写程序时的嵌套查询类似，并且可以用上被驱动表的索引，所以我们称之为“Index Nested-Loop Join”，简称NLJ。它对应的流程图如下所示：  </p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112610107.png" alt="image-20220327112610107" style="zoom:80%;" />

<p>在这个流程里：</p>
<ol>
<li>对驱动表t1做了全表扫描，这个过程需要扫描100行；</li>
<li>而对于每一行R，根据a字段去表t2查找，走的是树搜索过程。由于我们构造的数据都是一一对应的，因此每次的搜索过程都只扫描一行，也是总共扫描100行；</li>
<li>所以，整个执行流程，总扫描行数是200。</li>
</ol>
<p>小结：</p>
<blockquote>
<ul>
<li>保证被驱动表的JOIN字段已经创建了索引</li>
<li>需要JOIN 的字段，数据类型保持绝对一致</li>
<li>LEFT JOIN 时，选择小表作为驱动表， 大表作为被驱动表，减少外层循环的次数</li>
<li>INNER JOIN 时，MySQL会自动将小结果集的表选为驱动表，选择相信MySQL优化策略</li>
<li>能够直接多表关联的尽量直接关联，不用子查询。(减少查询的趟数)</li>
<li>不建议使用子查询，建议将子查询SQL拆开结合程序多次查询，或使用 JOIN 来代替子查询</li>
<li>衍生表建不了索引  </li>
</ul>
</blockquote>
<h2 id="4、子查询优化"><a href="#4、子查询优化" class="headerlink" title="4、子查询优化"></a>4、子查询优化</h2><p>MySQL从4.1版本开始支持子查询，使用子查询可以进行SELECT语句的嵌套查询，即一个SELECT查询的结果作为另一个SELECT语句的条件。 子查询可以一次性完成很多逻辑上需要多个步骤才能完成的SQL操作 。  </p>
<p>子查询是 MySQL 的一项重要的功能，可以帮助我们通过一个 SQL 语句实现比较复杂的查询。但是，子查询的执行效率不高。原因：</p>
<ul>
<li>执行子查询时，MySQL需要为内层查询语句的查询结果建立一个临时表 ，然后外层查询语句从临时表中查询记录。查询完毕后，再撤销这些临时表 。这样会消耗过多的CPU和IO资源，产生大量的慢查询。</li>
<li>子查询的结果集存储的临时表，不论是内存临时表还是磁盘临时表都不会存在索引 ，所以查询性能会受到一定的影响。</li>
<li>对于返回结果集比较大的子查询，其对查询性能的影响也就越大。</li>
</ul>
<p>在MySQL中，可以使用连接（JOIN）查询来替代子查询。连接查询不需要建立临时表 ，其速度比子查询要快 ，如果查询中使用索引的话，性能就会更好。  </p>
<blockquote>
<p>结论：尽量不要使用NOT IN 或者 NOT EXISTS，用LEFT JOIN xxx ON xx WHERE xx IS NULL替代  </p>
</blockquote>
<h2 id="5、排序优化"><a href="#5、排序优化" class="headerlink" title="5、排序优化"></a>5、排序优化</h2><h4 id="1、排序优化"><a href="#1、排序优化" class="headerlink" title="1、排序优化"></a>1、排序优化</h4><p>问题：在 WHERE 条件字段上加索引，但是为什么在 ORDER BY 字段上还要加索引呢？<br>优化建议：</p>
<ol>
<li>SQL 中，可以在 WHERE 子句和 ORDER BY 子句中使用索引，目的是在 WHERE 子句中避免全表扫描 ，在 ORDER BY 子句避免使用 FileSort 排序 。当然，某些情况下全表扫描，或者 FileSort 排序不一定比索引慢。但总的来说，我们还是要避免，以提高查询效率。</li>
<li>尽量使用 Index 完成 ORDER BY 排序。如果 WHERE 和 ORDER BY 后面是相同的列就使用单索引列；如果不同就使用联合索引。</li>
<li>无法使用 Index 时，需要对 FileSort 方式进行调优。  </li>
</ol>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">INDEX</span> a_b_c<span class="token punctuation">(</span>a<span class="token punctuation">,</span>b<span class="token punctuation">,</span>c<span class="token punctuation">)</span>
<span class="token keyword">order</span> <span class="token keyword">by</span> 能使用索引最左前缀
<span class="token operator">-</span> <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> a
<span class="token operator">-</span> <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> a<span class="token punctuation">,</span>b
<span class="token operator">-</span> <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> a<span class="token punctuation">,</span>b<span class="token punctuation">,</span>c
<span class="token operator">-</span> <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> a <span class="token keyword">DESC</span><span class="token punctuation">,</span>b <span class="token keyword">DESC</span><span class="token punctuation">,</span>c <span class="token keyword">DESC</span>

如果<span class="token keyword">WHERE</span>使用索引的最左前缀定义为常量，则<span class="token keyword">order</span> <span class="token keyword">by</span> 能使用索引
<span class="token operator">-</span> <span class="token keyword">WHERE</span> a <span class="token operator">=</span> const <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> b<span class="token punctuation">,</span>c
<span class="token operator">-</span> <span class="token keyword">WHERE</span> a <span class="token operator">=</span> const <span class="token operator">AND</span> b <span class="token operator">=</span> const <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> c
<span class="token operator">-</span> <span class="token keyword">WHERE</span> a <span class="token operator">=</span> const <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> b<span class="token punctuation">,</span>c
<span class="token operator">-</span> <span class="token keyword">WHERE</span> a <span class="token operator">=</span> const <span class="token operator">AND</span> b <span class="token operator">></span> const <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> b<span class="token punctuation">,</span>c

不能使用索引进行排序
<span class="token operator">-</span> <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> a <span class="token keyword">ASC</span><span class="token punctuation">,</span>b <span class="token keyword">DESC</span><span class="token punctuation">,</span>c <span class="token keyword">DESC</span> <span class="token comment">/* 排序不一致 */</span>
<span class="token operator">-</span> <span class="token keyword">WHERE</span> g <span class="token operator">=</span> const <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> b<span class="token punctuation">,</span>c <span class="token comment">/*丢失a索引*/</span>
<span class="token operator">-</span> <span class="token keyword">WHERE</span> a <span class="token operator">=</span> const <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> c <span class="token comment">/*丢失b索引*/</span>
<span class="token operator">-</span> <span class="token keyword">WHERE</span> a <span class="token operator">=</span> const <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> a<span class="token punctuation">,</span>d <span class="token comment">/*d不是索引的一部分*/</span>
<span class="token operator">-</span> <span class="token keyword">WHERE</span> a <span class="token operator">in</span> <span class="token punctuation">(</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span> <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> b<span class="token punctuation">,</span>c <span class="token comment">/*对于排序来说，多个相等条件也是范围查询*/</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="6、GROUP-BY优化"><a href="#6、GROUP-BY优化" class="headerlink" title="6、GROUP BY优化"></a>6、GROUP BY优化</h2><ul>
<li>group by 使用索引的原则几乎跟order by一致 ，group by 即使没有过滤条件用到索引，也可以直接<br>  使用索引。</li>
<li>group by 先排序再分组，遵照索引建的最佳左前缀法则</li>
<li>当无法使用索引列，增大 max_length_for_sort_data 和 sort_buffer_size 参数的设置</li>
<li>where效率高于having，能写在where限定的条件就不要写在having中了</li>
<li>减少使用order by，和业务沟通能不排序就不排序，或将排序放到程序端去做。Order by、group by、distinct这些语句较为耗费CPU，数据库的CPU资源是极其宝贵的。</li>
<li>包含了order by、group by、distinct这些查询的语句，where条件过滤出来的结果集请保持在1000行<br>  以内，否则SQL会很慢。</li>
</ul>
<h2 id="7、优化分页查询"><a href="#7、优化分页查询" class="headerlink" title="7、优化分页查询"></a>7、优化分页查询</h2><p><strong>优化思路一</strong><br>在索引上完成排序分页操作，最后根据主键关联回原表查询所需要的其他列内容。  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> <span class="token operator">*</span> <span class="token keyword">FROM</span> student t<span class="token punctuation">,</span><span class="token punctuation">(</span><span class="token keyword">SELECT</span> id <span class="token keyword">FROM</span> student <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> id <span class="token keyword">LIMIT</span> <span class="token number">2000000</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">)</span>
a W
HERE t<span class="token punctuation">.</span>id <span class="token operator">=</span> a<span class="token punctuation">.</span>id<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112617657.png" alt="image-20220327112617657" style="zoom:80%;" />

<p><strong>优化思路二</strong><br>该方案适用于主键自增的表，可以把Limit 查询转换成某个位置的查询 。  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">SELECT</span> <span class="token operator">*</span> <span class="token keyword">FROM</span> student <span class="token keyword">WHERE</span> id <span class="token operator">></span> <span class="token number">2000000</span> <span class="token keyword">LIMIT</span> <span class="token number">10</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112623314.png" alt="image-20220327112623314" style="zoom:80%;" />

<h2 id="8、优先考虑覆盖索引"><a href="#8、优先考虑覆盖索引" class="headerlink" title="8、优先考虑覆盖索引"></a>8、优先考虑覆盖索引</h2><h4 id="1、什么是覆盖索引？"><a href="#1、什么是覆盖索引？" class="headerlink" title="1、什么是覆盖索引？"></a>1、什么是覆盖索引？</h4><p>理解方式一：索引是高效找到行的一个方法，但是一般数据库也能使用索引找到一个列的数据，因此它不必读取整个行。毕竟索引叶子节点存储了它们索引的数据；当能通过读取索引就可以得到想要的数据，那就不需要读取行了。一个索引包含了满足查询结果的数据就叫做覆盖索引。<br>理解方式二：非聚簇复合索引的一种形式，它包括在查询里的SELECT、JOIN和WHERE子句用到的所有列（即建索引的字段正好是覆盖查询条件中所涉及的字段）。<br>简单说就是， 索引列+主键 包含 SELECT 到 FROM之间查询的列 。  </p>
<h4 id="2、覆盖索引的利弊"><a href="#2、覆盖索引的利弊" class="headerlink" title="2、覆盖索引的利弊"></a>2、覆盖索引的利弊</h4><p>好处：</p>
<ol>
<li>避免Innodb表进行索引的二次查询（回表）</li>
<li>可以把随机IO变成顺序IO加快查询效率</li>
</ol>
<p>弊端：索引字段的维护 总是有代价的。因此，在建立冗余索引来支持覆盖索引时就需要权衡考虑了。这是业务<br>DBA，或者称为业务数据架构师的工作 。</p>
<h2 id="9、如何给字符串添加索引"><a href="#9、如何给字符串添加索引" class="headerlink" title="9、如何给字符串添加索引"></a>9、如何给字符串添加索引</h2><p>有一张教师表，表定义如下：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token keyword">table</span> teacher<span class="token punctuation">(</span>
    ID <span class="token keyword">bigint</span> <span class="token keyword">unsigned</span> <span class="token keyword">primary</span> <span class="token keyword">key</span><span class="token punctuation">,</span>
    email <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">64</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">)</span><span class="token keyword">engine</span><span class="token operator">=</span><span class="token keyword">innodb</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>讲师要使用邮箱登录，所以业务代码中一定会出现类似于这样的语句：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">select</span> col1<span class="token punctuation">,</span> col2 <span class="token keyword">from</span> teacher <span class="token keyword">where</span> email<span class="token operator">=</span><span class="token string">'xxx'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>如果email这个字段上没有索引，那么这个语句就只能做全表扫描 。  </p>
<h4 id="1、前缀索引"><a href="#1、前缀索引" class="headerlink" title="1、前缀索引"></a>1、前缀索引</h4><p>MySQL是支持前缀索引的。默认地，如果你创建索引的语句不指定前缀长度，那么索引就会包含整个字<br>符串。  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">alter</span> <span class="token keyword">table</span> teacher <span class="token keyword">add</span> <span class="token keyword">index</span> index1<span class="token punctuation">(</span>email<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">#或</span>
mysql<span class="token operator">></span> <span class="token keyword">alter</span> <span class="token keyword">table</span> teacher <span class="token keyword">add</span> <span class="token keyword">index</span> index2<span class="token punctuation">(</span>email<span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>这两种不同的定义在数据结构和存储上有什么区别呢？下图就是这两个索引的示意图 :</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112631006.png" alt="image-20220327112631006" style="zoom:80%;" />

<p>以及  </p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112636936.png" alt="image-20220327112636936" style="zoom:80%;" />

<p>如果使用的是index1（即email整个字符串的索引结构），执行顺序是这样的：</p>
<ol>
<li>从index1索引树找到满足索引值是’ <a href="mailto:&#x7a;&#x68;&#97;&#110;&#103;&#x73;&#x73;&#x78;&#x79;&#x7a;&#x40;&#x78;&#120;&#x78;&#x2e;&#99;&#111;&#109;">&#x7a;&#x68;&#97;&#110;&#103;&#x73;&#x73;&#x78;&#x79;&#x7a;&#x40;&#x78;&#120;&#x78;&#x2e;&#99;&#111;&#109;</a> ’的这条记录，取得ID2的值；</li>
<li>到主键上查到主键值是ID2的行，判断email的值是正确的，将这行记录加入结果集；</li>
<li>取index1索引树上刚刚查到的位置的下一条记录，发现已经不满足email=’ <a href="mailto:&#122;&#104;&#x61;&#x6e;&#103;&#115;&#x73;&#x78;&#x79;&#122;&#x40;&#x78;&#120;&#x78;&#46;&#x63;&#x6f;&#x6d;">&#122;&#104;&#x61;&#x6e;&#103;&#115;&#x73;&#x78;&#x79;&#122;&#x40;&#x78;&#120;&#x78;&#46;&#x63;&#x6f;&#x6d;</a> ’的<br> 条件了，循环结束。</li>
</ol>
<p>这个过程中，只需要回主键索引取一次数据，所以系统认为只扫描了一行。  </p>
<p>如果使用的是index2（即email(6)索引结构），执行顺序是这样的：</p>
<ol>
<li>从index2索引树找到满足索引值是’zhangs’的记录，找到的第一个是ID1；</li>
<li>到主键上查到主键值是ID1的行，判断出email的值不是’ <a href="mailto:&#122;&#104;&#x61;&#110;&#103;&#115;&#x73;&#120;&#x79;&#122;&#64;&#x78;&#x78;&#120;&#46;&#99;&#111;&#109;">&#122;&#104;&#x61;&#110;&#103;&#115;&#x73;&#120;&#x79;&#122;&#64;&#x78;&#x78;&#120;&#46;&#99;&#111;&#109;</a> ’，这行记录丢弃；</li>
<li>取index2上刚刚查到的位置的下一条记录，发现仍然是’zhangs’，取出ID2，再到ID索引上取整行然<br> 后判断，这次值对了，将这行记录加入结果集；</li>
<li>重复上一步，直到在idxe2上取到的值不是’zhangs’时，循环结束。</li>
</ol>
<p>也就是说使用前缀索引，定义好长度，就可以做到既节省空间，又不用额外增加太多的查询成本。前面已经讲过区分度，区分度越高越好。因为区分度越高，意味着重复的键值越少。  </p>
<h4 id="2、前缀索引对覆盖索引的影响"><a href="#2、前缀索引对覆盖索引的影响" class="headerlink" title="2、前缀索引对覆盖索引的影响"></a>2、前缀索引对覆盖索引的影响</h4><p>使用前缀索引就用不上覆盖索引对查询性能的优化了，这也是你在选择是否使用前缀索引时需要考虑的一个因素。  </p>
<h2 id="10、索引下推"><a href="#10、索引下推" class="headerlink" title="10、索引下推"></a>10、索引下推</h2><p>Index Condition Pushdown(ICP)是MySQL 5.6中新特性，是一种在存储引擎层使用索引过滤数据的一种优化方式。ICP可以减少存储引擎访问基表的次数以及MySQL服务器访问存储引擎的次数。  </p>
<h4 id="1、使用前后的扫描过程"><a href="#1、使用前后的扫描过程" class="headerlink" title="1、使用前后的扫描过程"></a>1、使用前后的扫描过程</h4><p><strong>在不使用ICP索引扫描的过程：</strong></p>
<p>storage层：只将满足index key条件的索引记录对应的整行记录取出，返回给server层<br>server 层：对返回的数据，使用后面的where条件过滤，直至返回最后一行 </p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112643766.png" alt="image-20220327112643766" style="zoom:80%;" />

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112649987.png" alt="image-20220327112649987" style="zoom:80%;" />

<p><strong>使用ICP扫描的过程：</strong><br>storage层：<br>首先将index key条件满足的索引记录区间确定，然后在索引上使用index filter进行过滤。将满足的index<br>filter条件的索引记录才去回表取出整行记录返回server层。不满足index filter条件的索引记录丢弃，不回<br>表、也不会返回server层。<br>server 层：<br>对返回的数据，使用table filter条件做最后的过滤</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112655872.png" alt="image-20220327112655872" style="zoom:80%;" />

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112703433.png" alt="image-20220327112703433" style="zoom:80%;" />

<p><strong>使用前后的成本差别</strong><br>使用前，存储层多返回了需要被index filter过滤掉的整行记录<br>使用ICP后，直接就去掉了不满足index filter条件的记录，省去了他们回表和传递到server层的成本。<br>ICP的 加速效果 取决于在存储引擎内通过 ICP筛选 掉的数据的比例。  </p>
<h4 id="2、ICP的使用条件"><a href="#2、ICP的使用条件" class="headerlink" title="2、ICP的使用条件"></a>2、ICP的使用条件</h4><p>ICP的使用条件：</p>
<ul>
<li>只能用于二级索引(secondary index)</li>
<li>explain显示的执行计划中type值（join 类型）为 range 、 ref 、 eq_ref 或者 ref_or_null </li>
<li>并非全部where条件都可以用ICP筛选，如果where条件的字段不在索引列中，还是要读取整表的记录<br>  到server端做where过滤</li>
<li>ICP可以用于MyISAM和InnnoDB存储引擎</li>
<li>MySQL 5.6版本的不支持分区表的ICP功能，5.7版本的开始支持</li>
<li>当SQL使用覆盖索引时，不支持ICP优化方法</li>
</ul>
<h4 id="3、ICP使用案例"><a href="#3、ICP使用案例" class="headerlink" title="3、ICP使用案例"></a>3、ICP使用案例</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SELECT</span> <span class="token operator">*</span> <span class="token keyword">FROM</span> tuser
<span class="token keyword">WHERE</span> NAME <span class="token operator">LIKE</span> <span class="token string">'张%'</span>
<span class="token operator">AND</span> age <span class="token operator">=</span> <span class="token number">10</span>
<span class="token operator">AND</span> ismale <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112713543.png" alt="image-20220327112713543" style="zoom:80%;" />

<h2 id="11、普通索引-vs-唯一索引"><a href="#11、普通索引-vs-唯一索引" class="headerlink" title="11、普通索引 vs 唯一索引"></a>11、普通索引 vs 唯一索引</h2><p>从性能的角度考虑，你选择唯一索引还是普通索引呢？选择的依据是什么呢？<br>假设，我们有一个主键列为ID的表，表中有字段k，并且在k上有索引，假设字段 k 上的值都不重复。这个表的建表语句是：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">create</span> <span class="token keyword">table</span> test<span class="token punctuation">(</span>
    id <span class="token keyword">int</span> <span class="token keyword">primary</span> <span class="token keyword">key</span><span class="token punctuation">,</span>
    k <span class="token keyword">int</span> <span class="token operator">not</span> <span class="token boolean">null</span><span class="token punctuation">,</span>
    name <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">index</span> <span class="token punctuation">(</span>k<span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token keyword">engine</span><span class="token operator">=</span><span class="token keyword">InnoDB</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>表中R1~R5的(ID,k)值分别为(100,1)、(200,2)、(300,3)、(500,5)和(600,6)。  </p>
<h4 id="1、查询过程"><a href="#1、查询过程" class="headerlink" title="1、查询过程"></a>1、查询过程</h4><p>假设，执行查询的语句是 select id from test where k=5。</p>
<ul>
<li>对于普通索引来说，查找到满足条件的第一个记录(5,500)后，需要查找下一个记录，直到碰到第一个不满足k=5条件的记录。</li>
<li>对于唯一索引来说，由于索引定义了唯一性，查找到第一个满足条件的记录后，就会停止继续检索。</li>
</ul>
<p>那么，这个不同带来的性能差距会有多少呢？答案是， 微乎其微。</p>
<h4 id="2、更新过程"><a href="#2、更新过程" class="headerlink" title="2、更新过程"></a>2、更新过程</h4><p>为了说明普通索引和唯一索引对更新语句性能的影响这个问题，介绍一下change buffer。</p>
<p>当需要更新一个数据页时，如果数据页在内存中就直接更新，而如果这个数据页还没有在内存中的话，在不影响数据一致性的前提下， InooDB会将这些更新操作缓存在change buffer中 ，这样就不需要从磁盘中读入这个数据页了。在下次查询需要访问这个数据页的时候，将数据页读入内存，然后执行change buffer中与这个页有关的作。通过这种方式就能保证这个数据逻辑的正确性。</p>
<p>将change buffer中的操作应用到原数据页，得到最新结果的过程称为 merge 。除了 访问这个数据页 会触发merge外，系统有 后台线程会定期 merge。在 数据库正常关闭（shutdown） 的过程中，也会执行merge 操作。</p>
<p>如果能够将更新操作先记录在change buffer， 减少读磁盘 ，语句的执行速度会得到明显的提升。而且，数据读入内存是需要占用 buffer pool 的，所以这种方式还能够 避免占用内存 ，提高内存利用率。</p>
<p>唯一索引的更新就不能使用change buffer ，实际上也只有普通索引可以使用。如果要在这张表中插入一个新记录(4,400)的话，InnoDB的处理流程是怎样的？  </p>
<h4 id="3、change-buffer的使用场景"><a href="#3、change-buffer的使用场景" class="headerlink" title="3、change buffer的使用场景"></a>3、change buffer的使用场景</h4><p>1、普通索引和唯一索引应该怎么选择？其实，这两类索引在查询能力上是没差别的，主要考虑的是对 更新性能 的影响。所以，建议你 尽量选择普通索引 。</p>
<p>2、在实际使用中会发现， 普通索引 和 change buffer 的配合使用，对于 数据量大 的表的更新优化还是很明显的。</p>
<p>3、如果所有的更新后面，都马上 伴随着对这个记录的查询 ，那么你应该 关闭change buffer 。而在其他情况下，change buffer都能提升更新性能。</p>
<p>4、由于唯一索引用不上change buffer的优化机制，因此如果 业务可以接受 ，从性能角度出发建议优先考虑非唯一索引。但是如果”业务可能无法确保”的情况下，怎么处理呢？</p>
<ul>
<li>首先， 业务正确性优先 。我们的前提是“业务代码已经保证不会写入重复数据”的情况下，讨论性能问题。如果业务不能保证，或者业务就是要求数据库来做约束，那么没得选，必须创建唯一索引。这种情况下，本节的意义在于，如果碰上了大量插入数据慢、内存命中率低的时候，给你多提供一个排查思路。</li>
<li>然后，在一些“ 归档库 ”的场景，你是可以考虑使用唯一索引的。比如，线上数据只需要保留半年，然后历史数据保存在归档库。这时候，归档数据已经是确保没有唯一键冲突了。要提高归档效率，可以考虑把表里面的唯一索引改成普通索引。  </li>
</ul>
<h2 id="12、其它查询优化策略"><a href="#12、其它查询优化策略" class="headerlink" title="12、其它查询优化策略"></a>12、其它查询优化策略</h2><h4 id="1、COUNT-与COUNT-具体字段-效率"><a href="#1、COUNT-与COUNT-具体字段-效率" class="headerlink" title="1、COUNT(*)与COUNT(具体字段)效率"></a>1、COUNT(*)与COUNT(具体字段)效率</h4><p>问：在 MySQL 中统计数据表的行数，可以使用三种方式： SELECT COUNT(*) 、 SELECT COUNT(1) 和SELECT COUNT(具体字段) ，使用这三者之间的查询效率是怎样的？  </p>
<h4 id="2、关于SELECT"><a href="#2、关于SELECT" class="headerlink" title="2、关于SELECT(*)"></a>2、关于SELECT(*)</h4><p>在表查询中，建议明确字段，不要使用 * 作为查询的字段列表，推荐使用SELECT &lt;字段列表&gt; 查询。原因：</p>
<p>① MySQL 在解析的过程中，会通过 查询数据字典 将”*”按序转换成所有列名，这会大大的耗费资源和时间。</p>
<p>② 无法使用 覆盖索引 </p>
<h4 id="3、LIMIT-1-对优化的影响"><a href="#3、LIMIT-1-对优化的影响" class="headerlink" title="3、LIMIT 1 对优化的影响"></a>3、LIMIT 1 对优化的影响</h4><p>针对的是会扫描全表的 SQL 语句，如果你可以确定结果集只有一条，那么加上 LIMIT 1 的时候，当找到一条结果的时候就不会继续扫描了，这样会加快查询速度。</p>
<p>如果数据表已经对字段建立了唯一索引，那么可以通过索引进行查询，不会全表扫描的话，就不需要加上 LIMIT 1 了。  </p>
<h4 id="4、多使用COMMIT"><a href="#4、多使用COMMIT" class="headerlink" title="4、多使用COMMIT"></a>4、多使用COMMIT</h4><p>只要有可能，在程序中尽量多使用 COMMIT，这样程序的性能得到提高，需求也会因为 COMMIT 所释放的资源而减少。<br>COMMIT 所释放的资源：</p>
<ul>
<li>回滚段上用于恢复数据的信息</li>
<li>被程序语句获得的锁</li>
<li>redo / undo log buffer 中的空间</li>
<li>管理上述 3 种资源中的内部花费  </li>
</ul>
<h2 id="13、自增主键的问题"><a href="#13、自增主键的问题" class="headerlink" title="13、自增主键的问题"></a>13、自增主键的问题</h2><h4 id="1、自增ID的问题"><a href="#1、自增ID的问题" class="headerlink" title="1、自增ID的问题"></a>1、自增ID的问题</h4><p>自增ID做主键，简单易懂，几乎所有数据库都支持自增类型，只是实现上各自有所不同而已。自增ID除了简单，其他都是缺点，总体来看存在以下几方面的问题：</p>
<ol>
<li>可靠性不高<br> 存在自增ID回溯的问题，这个问题直到最新版本的MySQL 8.0才修复。</li>
<li>安全性不高<br> 对外暴露的接口可以非常容易猜测对应的信息。比如：/User/1/这样的接口，可以非常容易猜测用户ID的值为多少，总用户数量有多少，也可以非常容易地通过接口进行数据的爬取。</li>
<li>性能差<br> 自增ID的性能较差，需要在数据库服务器端生成。</li>
<li>交互多<br> 业务还需要额外执行一次类似 last_insert_id() 的函数才能知道刚才插入的自增值，这需要多一次的网络交互。在海量并发的系统中，多1条SQL，就多一次性能上的开销。</li>
<li>局部唯一性<br> 最重要的一点，自增ID是局部唯一，只在当前数据库实例中唯一，而不是全局唯一，在任意服务器间都是唯一的。对于目前分布式系统来说，这简直就是噩梦  </li>
</ol>
<h4 id="2、推荐的主键设计"><a href="#2、推荐的主键设计" class="headerlink" title="2、推荐的主键设计"></a>2、推荐的主键设计</h4><p>非核心业务 ：对应表的主键自增ID，如告警、日志、监控等信息。</p>
<p>核心业务 ：主键设计至少应该是全局唯一且是单调递增。全局唯一保证在各系统之间都是唯一的，单调递增是希望插入时不影响数据库性能。</p>
<p>这里推荐最简单的一种主键设计：UUID。  </p>
<p><strong>UUID的特点</strong>：全局唯一，占用36字节，数据无序，插入性能差。  </p>
<p><strong>认识UUID：</strong></p>
<ul>
<li>为什么UUID是全局唯一的？</li>
<li>为什么UUID占用36个字节？</li>
<li>为什么UUID是无序的？  </li>
</ul>
<p>MySQL数据库的UUID组成如下所示：  </p>
<pre class="line-numbers language-none"><code class="language-none">UUID &#x3D; 时间+UUID版本（16字节）- 时钟序列（4字节） - MAC地址（12字节）<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>我们以UUID值e0ea12d4-6473-11eb-943c-00155dbaa39d举例：  </p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112722964.png" alt="image-20220327112722964" style="zoom:80%;" />

<p><strong>为什么UUID是全局唯一的？</strong></p>
<ul>
<li>在UUID中时间部分占用60位，存储的类似TIMESTAMP的时间戳，但表示的是从1582-10-15 00：00：00.00到现在的100ns的计数。可以看到UUID存储的时间精度比TIMESTAMPE更高，时间维度发生重复的概率降低到1/100ns。</li>
</ul>
<p>时钟序列是为了避免时钟被回拨导致产生时间重复的可能性。MAC地址用于全局唯一。</p>
<p><strong>为什么UUID占用36个字节？</strong></p>
<ul>
<li>UUID根据字符串进行存储，设计时还带有无用”-“字符串，因此总共需要36个字节。</li>
</ul>
<p><strong>为什么UUID是随机无序的呢？</strong></p>
<ul>
<li>因为UUID的设计中，将时间低位放在最前面，而这部分的数据是一直在变化的，并且是无序。</li>
</ul>
<p><strong>改造UUID</strong><br>若将时间高低位互换，则时间就是单调递增的了，也就变得单调递增了。MySQL 8.0可以更换时间低位和时间高位的存储方式，这样UUID就是有序的UUID了。</p>
<p>MySQL 8.0还解决了UUID存在的空间占用的问题，除去了UUID字符串中无意义的”-“字符串，并且将字符串用二进制类型保存，这样存储空间降低为了16字节。</p>
<p>可以通过MySQL8.0提供的uuid_to_bin函数实现上述功能，同样的，MySQL也提供了bin_to_uuid函数进行<br>转化：  </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SET</span> <span class="token variable">@uuid</span> <span class="token operator">=</span> UUID<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">SELECT</span> <span class="token variable">@uuid</span><span class="token punctuation">,</span>uuid_to_bin<span class="token punctuation">(</span><span class="token variable">@uuid</span><span class="token punctuation">)</span><span class="token punctuation">,</span>uuid_to_bin<span class="token punctuation">(</span><span class="token variable">@uuid</span><span class="token punctuation">,</span><span class="token boolean">TRUE</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327112737175.png" alt="image-20220327112737175" style="zoom:80%;" />

<p>通过函数uuid_to_bin(@uuid,true)将UUID转化为有序UUID了。全局唯一 + 单调递增，这不就是我们想要的主键！  </p>
<p>好啦，到这里我们的MySQL索引优化就讲解完拉！</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Skyu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://kuangty.gitee.io/2021/10/31/MySQL/MySQL%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96%E4%B8%8E%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96/">https://kuangty.gitee.io/2021/10/31/MySQL/MySQL%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96%E4%B8%8E%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Skyu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/MySQL-%E7%B4%A2%E5%BC%95%E4%BC%98%E5%8C%96%E4%B8%8E%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96/">
                                    <span class="chip bg-color">MySQL 索引优化与查询优化</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/10/31/MySQL/explain/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/1.jpg" class="responsive-img" alt="explain">
                        
                        <span class="card-title">explain</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-10-31
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/MySQL/" class="post-category">
                                    MySQL
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/explain/">
                        <span class="chip bg-color">explain</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/10/31/MySQL/MySQL%E4%BA%8B%E5%8A%A1/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/3.jpg" class="responsive-img" alt="冰冰教你学 MySQL 事务">
                        
                        <span class="card-title">冰冰教你学 MySQL 事务</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-10-31
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/MySQL/" class="post-category">
                                    MySQL
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/MySQL-%E4%BA%8B%E5%8A%A1/">
                        <span class="chip bg-color">MySQL 事务</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Gtwff</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">577.4k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2019";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/kuangtianyu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1575235124@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1575235124" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1575235124" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/kuang-tian-yu-59" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/kuang-tian-yu-59" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
